package com.st.warehouse.utils;
  
import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

import okhttp3.Callback;
import okhttp3.MediaType;  
import okhttp3.OkHttpClient;  
import okhttp3.Request;  
import okhttp3.RequestBody;
import okhttp3.Response;

public class HttpRequestUtils {
  
    private static final OkHttpClient client = new OkHttpClient();  
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static String HOST_URL = "http://192.168.31.46:1221";  // 本地
  
    // 发送GET请求  
    public static void get(String url, Callback callback) {
        System.out.println(HOST_URL.concat(url));
        Request request = new Request.Builder()  
                .url(HOST_URL.concat(url))
                .get()
                .build();  
  
        client.newCall(request).enqueue(callback);  
    }  
  
    // 发送POST请求（JSON数据）  
    public static void post(String url, JSONObject json, Callback callback) {
        RequestBody body = RequestBody.create(JSON, String.valueOf(json));
        Request request = new Request.Builder()  
                .url(HOST_URL.concat(url))
                .post(body)  
                .build();  
  
        client.newCall(request).enqueue(callback);  
    }

    // 发送POST请求（表单数据）
    public static void post(String url, RequestBody requestBody, Callback callback) {
        Request request = new Request.Builder()
                .url(HOST_URL.concat(url))
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(callback);
    }

    /**
     * 获取接口返回数据
     */
    public static JSONObject result(Response response) throws IOException {
        if (response != null && response.isSuccessful() && response.body() != null) {
            String responseStr = response.body().string();
            if (StringUtils.isJson(responseStr)) {
                return JSONObject.parseObject(responseStr);
            } else {
                return getErrorJson("网络异常，数据异常");
            }
        } else {
            return getErrorJson("网络异常，连接超时");
        }
    }

    /**
     * 获取报错的信息
     */
    private static JSONObject getErrorJson(String msg) {
        JSONObject data = new JSONObject();
        data.put("code", 500);
        data.put("success", false);
        data.put("msg", msg);
        return data;
    }
}